#import "dfhgwhruebvhrheymournrural.h"
#import "dfhgwhruebvhrheyluggagerecorder.h"
#import "dfhgwhruebvhrheyoutwarddelegate.h"
#import "dfhgwhruebvhrheythrivealternate.h"
#import "dfhgwhruebvhrheydelegatelimp.h"
#import "dfhgwhruebvhrheyyearlyquantifyViewController.h"
#import "dfhgwhruebvhrheymercyindependenceViewController.h"
#import "dfhgwhruebvhrheytragedymotivateViewController.h"
#import "dfhgwhruebvhrheyroomcatalogViewController.h"
@interface dfhgwhruebvhrheymercyindependenceViewController ()
@property (nonatomic, strong) dfhgwhruebvhrheymournrural *timer;
@end
@implementation dfhgwhruebvhrheymercyindependenceViewController {
    int cut_down;
    UIView *bgView;
    UIImageView *icon;
    UIScrollView *scrollView;
    UIView *containerView;
	UILabel *phoneText;
    dfhgwhruebvhrheythrivealternate *phone;
    UILabel *passText;
    dfhgwhruebvhrheythrivealternate *passwd;
	UIButton *eyeBtn;
    UIButton *sendBtn;
    UILabel *verificationLabel;
    UIView *verificationView;
    dfhgwhruebvhrheythrivealternate *verification;
    UIButton *forgetBtn;
    UIButton *loginBtn;
	UIButton *registerBtn;
}
- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inputChange:) name:UITextFieldTextDidChangeNotification object:nil];
	NSString *mobile = [[NSUserDefaults standardUserDefaults] stringForKey:dhgfywegwygeydwgratitudepreside];
	if (mobile.length) {
		phone.content = mobile;
		[[NSUserDefaults standardUserDefaults] removeObjectForKey:dhgfywegwygeydwgratitudepreside];
	}
}
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
- (dfhgwhruebvhrheymournrural *)timer {
    if (_timer == nil) {
        _timer = [[dfhgwhruebvhrheymournrural alloc] init];
    }
    return _timer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
	[self loadUI];
}
- (void)loadUI {
    cut_down = dhgfywegwygeydwleakconceal;
	[self configBackIcon:@"dhgfywegwygeydwcurvereciprocal"];
    bgView = [[UIView alloc] init];
    bgView.layer.cornerRadius = 20;
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    icon = [[UIImageView alloc] init];
    icon.image = [UIImage imageNamed:@"dhgfywegwygeydwpresideabsolute"];
    [bgView addSubview:icon];
    scrollView = [[UIScrollView alloc] init];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:scrollView];
    containerView = [[UIView alloc] init];
    containerView.backgroundColor = white_color.dhgfywegwygeydwlearneddesignate;
    [scrollView addSubview:containerView];
	phoneText = [[UILabel alloc] init];
	phoneText.text = @"Phone number";
	phoneText.font = [UIFont regular:16];
	phoneText.textColor = text_color1.dhgfywegwygeydwlearneddesignate;
	[containerView addSubview:phoneText];
    phone = [[dfhgwhruebvhrheythrivealternate alloc] init];
    [containerView addSubview:phone];
    phone.left_text = @"+63";
    phone.tag = 100;
    phone.rightBtn = nil;
    phone.placeholder = @"Please Enter Phone Number";
	passText = [[UILabel alloc] init];
	passText.text = @"Password";
	passText.font = [UIFont regular:16];
	passText.textColor = text_color1.dhgfywegwygeydwlearneddesignate;
	[containerView addSubview:passText];
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.tag = 200;
    rightBtn.frame = CGRectMake(0, 0, 24, 24);
    [rightBtn setImage:[UIImage imageNamed:@"dhgfywegwygeydwreceiptaffirm"] forState:UIControlStateSelected];
    [rightBtn setImage:[UIImage imageNamed:@"dhgfywegwygeydwaffirmsalesman"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(loginPageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    passwd = [[dfhgwhruebvhrheythrivealternate alloc] init];
    [containerView addSubview:passwd];
    passwd.rightBtn = rightBtn;
    passwd.tag = 101;
    passwd.secureTextEntry = YES;
    passwd.placeholder = @"Please enter a 6-digit password";
    sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
    sendBtn.frame = CGRectMake(0, 0, 70, 40);
    sendBtn.tag = 201;
    sendBtn.layer.cornerRadius = 8;
    [sendBtn setTitle:@"Send" forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(loginPageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    verificationView = [[UIView alloc] init];
    verificationLabel = [[UILabel alloc] init];
    verificationLabel.text = @"Verification code";
    verificationLabel.font = [UIFont regular:16];
    verificationLabel.textColor = text_color1.dhgfywegwygeydwlearneddesignate;
    [verificationView addSubview:verificationLabel];
    verificationView.hidden = YES;
    verification = [[dfhgwhruebvhrheythrivealternate alloc] init];
    [containerView addSubview:verification];
    verification.tag = 102;
    verification.rightBtn = sendBtn;
    verification.placeholder = @"A 6-digit OTP";
    [verificationView addSubview:verification];
    [containerView addSubview:verificationView];
	forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	forgetBtn.tag = 202;
	forgetBtn.titleLabel.font = [UIFont regular:14];
	[forgetBtn setTitle:@"Forgot password ？" forState:UIControlStateNormal];
	forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
	[forgetBtn setTitleColor:primary_color.dhgfywegwygeydwlearneddesignate forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(loginPageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:forgetBtn];
	loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	loginBtn.tag = 203;
	loginBtn.layer.cornerRadius = 10;
	loginBtn.titleLabel.font = [UIFont semiBold:18];
	loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
	[loginBtn setTitle:@"Login" forState:UIControlStateNormal];
	[loginBtn setTitleColor:white_color.dhgfywegwygeydwlearneddesignate forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginPageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:loginBtn];
	registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	registerBtn.tag = 204;
	registerBtn.layer.borderWidth = 1;
	registerBtn.layer.cornerRadius = 10;
	registerBtn.titleLabel.font = [UIFont semiBold:18];
	[registerBtn setTitle:@"Register" forState:UIControlStateNormal];
	[registerBtn setTitleColor:primary_color.dhgfywegwygeydwlearneddesignate forState:UIControlStateNormal];
	registerBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    [registerBtn addTarget:self action:@selector(loginPageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [containerView addSubview:registerBtn];
}
- (void)inputChange:(NSNotification *)not {
	UITextField *input = [not object];
	NSString *text = input.text;
	if (input.superview.tag == 100) {
		if ([text hasPrefix:@"8"] || [text hasPrefix:@"9"]) {
			if (text.length >= 10) {
				phone.content = [text substringToIndex:10];
                if ([phone.content dhgfywegwygeydwdesignatecommence] && passwd.content.length == 6) {
                    loginBtn.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
                }else {
                    loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
                }
            }else {
                phone.content = text;
                loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
            }
		}else {
			if (text.length >= 11) {
				phone.content = [text substringToIndex:11];
                if ([phone.content dhgfywegwygeydwdesignatecommence] && passwd.content.length == 6) {
                    loginBtn.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
                }else {
                    loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
                }
            }else {
                phone.content = text;
                loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
            }
		}
        [self verificationCodeShow:NO];
	}else if(input.superview.tag == 101){
		if(text.length >= 6) {
			passwd.content = [text substringToIndex:6];
			if([phone.content dhgfywegwygeydwdesignatecommence]) {
                if (verificationView.isHidden) {
                    [self.view endEditing:YES];
                }
                loginBtn.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
            }else {
                loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
            }
        }else {
            passwd.content = text;
            loginBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
        }
    }else {
        if(text.length >= 6) {
            verification.content = [text substringToIndex:6];
            if ([phone.content dhgfywegwygeydwdesignatecommence] && passwd.content.length == 6) {
                [self.view endEditing:YES];
            }
        }else {
            verification.content = text;
        }
    }
}
- (void)loginPageBtnAction:(UIButton *)sender {
	switch (sender.tag) {
		case 200: {
			sender.selected = !sender.selected;
			passwd.secureTextEntry = !sender.isSelected;
		}
			break;
        case 201: {
            NSLog(@"发送验证码");
            [self sendLoginSms];
        }
            break;
		case 202: {
            NSLog(@"忘记密码");
            dfhgwhruebvhrheytragedymotivateViewController *forgetVC = [[dfhgwhruebvhrheytragedymotivateViewController alloc] init];
            forgetVC.mobile = phone.content;
            forgetVC.isFromLogin = YES;
			[self.navigationController pushViewController:forgetVC animated:YES];
		}
			break;
		case 203: {
			if (phone.content.length == 0) {
				[self.view show:@"Mobile phone number cannot be empty"];
				return;
			}
			if (![phone.content dhgfywegwygeydwdesignatecommence]) {
				[self.view show:@"Please enter the correct format for the phone number，which must start with 9, 09, 8 or 08"];
				return;
			}
			if (passwd.content.length != 6) {
				[self.view show:@"please enter a 6-digit password"];
				return;
			}
            if (!verificationView.isHidden) {
                if (verification.content.length == 0) {
                    [self.view show:@"please enter a 6-digit code"];
                    return;
                }else {
                    [self login:phone.content withPasswd:passwd.content sms_code:verification.content];
                }
            }else {
                [self checkNewDevice:phone.content andPasswd:passwd.content];
            }
		}
			break;
		case 204:{
			dfhgwhruebvhrheyroomcatalogViewController *regVC = [[dfhgwhruebvhrheyroomcatalogViewController alloc] init];
			[self.navigationController pushViewController:regVC animated:YES];
		}
			break;
		default:
			break;
	}
}
- (void)verificationCodeShow:(BOOL)isShow {
    verificationView.hidden = !isShow;
    CGFloat height = isShow ? 135 : 19;
    [verificationView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
}
- (void)startTimer {
    sendBtn.enabled = NO;
    sendBtn.backgroundColor = [primary_color dhgfywegwygeydwlearneddesignate:0.4];
    [self.timer startWithAction:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateCutTime];
        });
    }];
}
- (void)backAction {
    if (_timer) {
        [_timer cancel];
        _timer = nil;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)updateCutTime {
    if (cut_down <= 1) {
        cut_down = dhgfywegwygeydwleakconceal;
        [_timer cancel];
        _timer = nil;
        sendBtn.enabled = YES;
        [sendBtn setTitle:@"Send" forState:UIControlStateNormal];
        sendBtn.backgroundColor = primary_color.dhgfywegwygeydwlearneddesignate;
    }else {
        cut_down -= 1;
        [sendBtn setTitle:[NSString stringWithFormat:@"%02ds", cut_down] forState:UIControlStateNormal];
    }
}
- (void)sendLoginSms {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"pgid"] = @"1";
    params[@"mobile"] = phone.content;
    [dfhgwhruebvhrheyoptionsaving.keyWindow startLoading];
    __weak typeof(self) weakSelf = self;
    [[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwawaitlamb path:newDeviceLoginCodeApi isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
        [dfhgwhruebvhrheyoptionsaving.keyWindow stopLoading];
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dfhgwhruebvhrheysternideology *model = [dfhgwhruebvhrheysternideology yy_modelWithJSON:json];
        if (model.code == 200) {
            [strongSelf startTimer];
        }else{
            [dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [dfhgwhruebvhrheyoptionsaving.keyWindow stopLoading];
    }];
}
- (void)checkNewDevice:(NSString *)mobile andPasswd:(NSString *)passwdText {
	NSString *phone = mobile;
	if ([mobile hasPrefix:@"0"]) {
		phone = [mobile substringFromIndex:1];
	}
	NSMutableDictionary *params = [NSMutableDictionary dictionary];
	params[@"password"] = passwdText;
	params[@"mobile"] = phone;
	params[@"pgid"] = @"1";
	params[@"dev_id"] = [dfhgwhruebvhrheyoptionsaving uuid].dhgfywegwygeydwscholarshiptexture;
	[dfhgwhruebvhrheyoptionsaving.keyWindow startLoading];
	__weak typeof(self) weakSelf = self;
	[[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwawaitlamb path:checkDeviceApi isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
        [dfhgwhruebvhrheyoptionsaving.keyWindow stopLoading];
		__strong typeof(weakSelf) strongSelf = weakSelf;
		dfhgwhruebvhrheydelegatelimp *model = [dfhgwhruebvhrheydelegatelimp yy_modelWithJSON:json];
		if (model.code == 200) {
			if (model.code_type == 0) {
				[strongSelf verificationCodeShow:YES];
			}else {
				[strongSelf login:phone withPasswd:passwdText sms_code:nil];
			}
		}else {
			[dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
		}
	} failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
		[dfhgwhruebvhrheyoptionsaving.keyWindow stopLoading];
	}];
}
- (void)login:(NSString *)mobile withPasswd:(NSString *)passwd sms_code:(nullable NSString *)code {
	NSString *riskJson = [dfhgwhruebvhrheyoptionsaving getRiskJsonData];
	NSMutableDictionary *params = [@{} mutableCopy];
	params[@"device_id"] = [[dfhgwhruebvhrheyoptionsaving uuid] dhgfywegwygeydwscholarshiptexture];
	params[@"mobile"] = mobile;
	params[@"pgid"] = @"1";
	params[@"password"] = passwd;
	params[@"type"] =  @"2";
	params[@"version"] = [dfhgwhruebvhrheyoptionsaving appVersionString];
	params[@"mobile"] = mobile;
	params[@"sms_code"] = code;
	params[@"rdata"] = riskJson;
	__weak typeof(self) weakSelf = self;
	[[dfhgwhruebvhrheyluggagerecorder shareInstance] dhgfywegwygeydwbarrierawait:dhgfywegwygeydwawaitlamb path:loginApi isEncrypt:YES withParams:params success:^(NSURLSessionDataTask * _Nonnull task, NSString * _Nonnull json) {
		[dfhgwhruebvhrheyoptionsaving.keyWindow stopLoading];
		__strong typeof(weakSelf) strongSelf = weakSelf;
		dfhgwhruebvhrheyoutwarddelegate *model = [dfhgwhruebvhrheyoutwarddelegate yy_modelWithJSON:json];
		if (model.code == 200) {
			[dfhgwhruebvhrheyoptionsaving saveUserInfo:json completion:^{
				[dfhgwhruebvhrheyoptionsaving uploadRiskDataByCatchId:@"4" andApplyId:nil withDetailId:nil];
				[strongSelf dismissViewControllerAnimated:YES completion:nil];
				[[NSNotificationCenter defaultCenter] postNotificationName:dhgfywegwygeydwembarrassurgent object:nil];
			}];
		}else {
			[dfhgwhruebvhrheyoptionsaving.keyWindow show:model.error];
		}
	} failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
		[dfhgwhruebvhrheyoptionsaving.keyWindow stopLoading];
	}];
}
- (void)viewDidLayoutSubviews {
	[super viewDidLayoutSubviews];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(48);
        make.left.bottom.right.equalTo(self.view);
    }];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);
        make.top.equalTo(bgView).offset(-40);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(icon.mas_bottom).offset(16);
        make.left.bottom.right.equalTo(bgView);
    }];
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        make.width.equalTo(scrollView);
    }];
	[phoneText mas_makeConstraints:^(MASConstraintMaker *make) {
		make.size.mas_equalTo(CGSizeMake(168, 24));
		make.top.equalTo(containerView).offset(16);
		make.left.equalTo(containerView).offset(12);
	}];
	[phone mas_makeConstraints:^(MASConstraintMaker *make) {
		make.height.mas_equalTo(56);
		make.centerX.equalTo(containerView);
        make.left.equalTo(containerView).offset(12);
        make.top.equalTo(phoneText.mas_bottom).offset(12);
	}];
	[passText mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.equalTo(phoneText);
		make.height.mas_equalTo(24);
		make.top.equalTo(phone.mas_bottom).offset(24);
	}];
	[passwd mas_makeConstraints:^(MASConstraintMaker *make) {
		make.height.mas_equalTo(56);
		make.left.equalTo(passText);
		make.centerX.equalTo(containerView);
		make.top.equalTo(passText.mas_bottom).offset(12);
	}];
    [verificationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(19).priorityMedium();
        make.top.equalTo(passwd.mas_bottom);
        make.left.right.equalTo(containerView);
    }];
    [verificationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(verificationView).offset(24);
        make.left.equalTo(verificationView).offset(12);
        make.size.mas_equalTo(CGSizeMake(136, 24));
    }];
    [verification mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(verificationLabel.mas_bottom).offset(12);
        make.height.mas_equalTo(56);
        make.left.equalTo(verificationLabel);
        make.centerX.equalTo(verificationView);
    }];
	[forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.equalTo(passwd);
		make.size.mas_equalTo(CGSizeMake(145, 23));
		make.top.equalTo(verificationView.mas_bottom);
	}];
	[loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.equalTo(forgetBtn);
		make.height.mas_equalTo(56);
		make.centerX.equalTo(containerView);
		make.top.equalTo(forgetBtn.mas_bottom).offset(40);
	}];
	[registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.equalTo(loginBtn);
		make.height.mas_equalTo(56);
		make.centerX.equalTo(containerView);
		make.top.equalTo(loginBtn.mas_bottom).offset(4);
        make.bottom.equalTo(containerView).offset(-50);
	}];
}
@end
